package com.xuyn.framework.web.controller;

import com.github.pagehelper.PageHelper;
import com.xuyn.common.utils.DateUtils;
import com.xuyn.common.utils.StringUtils;
import com.xuyn.common.utils.sql.SqlUtil;
import com.xuyn.framework.web.page.PageDomain;
import com.xuyn.framework.web.page.TableSupport;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * @ Program     : xuyn
 * @ Description : web层通用数据处理
 * @ Author      : Emason
 * @ Create      : 2019-09-19 10:16
 * @ Since       : 1.0
 **/
public class BaseController {

    /**
     *  将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.registerCustomEditor(Date.class,new PropertyEditorSupport(){
            @Override
            public void setAsText(String text) throws IllegalArgumentException {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize))
        {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

}
